<?php
namespace app\event;
use think\app\Service;
use think\facade\Request;
use think\facade\Route;
class InitRoute extends Service {

    /**
     * 
     */
    public function handle() {

        $system_array       = [ 'admin', 'api', 'pay'];

        // todo 直接获取 pathInfo 会导致请求异常，
        $path_info          = trim(explode('?', request()->url())[0], '/');

        $path_info_array    = explode('/', $path_info);
        $check_model        = $path_info_array[0];
        $addon              = in_array($check_model, $system_array) ? '' : $check_model;
        if($addon) {
            $module         = isset($path_info_array[1]) ? $path_info_array[1] : 'admin';
            $controller     = isset($path_info_array[2]) ? $path_info_array[2] : 'index';
            $method         = isset($path_info_array[3]) ? $path_info_array[3] : 'index';
            request()->addon($addon);
            // 动态绑定命名空间
            $this->app->setNamespace("addon\\" . $addon . '\\' . $module);
            // 动态设置应用目录
            $this->app->setAppPath($this->app->getRootPath() . 'addon' . DIRECTORY_SEPARATOR. $addon . DIRECTORY_SEPARATOR . $module . DIRECTORY_SEPARATOR);
        } else {
            $module         = isset($path_info_array[0]) ? $path_info_array[0] : 'admin';
            $controller     = isset($path_info_array[1]) ? $path_info_array[1] : 'index';
            $method         = isset($path_info_array[2]) ? $path_info_array[2] : 'index';
        }

        $path_info  = str_replace(".html", '', $path_info);
        $controller = str_replace(".html", '', $controller);
        $method     = str_replace(".html", '', $method);
        request()->module($module);

        // 动态添加路由
        Route::rule($path_info, $module . '/' . $controller . '/' . $method);
    }
}